package util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import model.Instrument;
import model.Piece;
import model.Sequence;

public class Converter {

	/**
	 * Converts a Mario Paint Composer Song into a Piece.<br>
	 * As MPC uses a wider range of pitches, some notes will be bottle-necked.
	 * @return The converted piece
	 */
	public static Piece convertMPCSong(String mpcFilePath) {
		String mpcFile;
		try {
			Scanner sc = new Scanner(FileIO.getResourceAsStream(mpcFilePath));
			mpcFile = sc.next();
		} catch(IOException ioe) {
			System.out.println("Couldn't find MPC file to convert");
			return new Piece("Placeholder", 1000);
		}

		String[] columns = mpcFile.split("\\*")[1].split(":");
		Sequence[] sequences = new Sequence[19];
		for(int i = 0; i < sequences.length; i++) {
			sequences[i] = new Sequence(
				Instrument.values()[i%Instrument.values().length], 100, 100
			);
		}
		for(int i = 0; i < columns.length-1; i++) {
			String[] notes = columns[i].split("\\+");
			for(String note : notes) {
				if(note.length() != 2) continue;
				int index = note.charAt(0) - 'a';
				int pitch = note.charAt(1) - 'e';
				pitch += 1;

				//Bottleneck pitches outside our range (1-9)
				if(pitch < 1) pitch = 1;
				else if(pitch > 9) pitch = 9;
				
				sequences[index].setNote(i, pitch);
			}
		}

		List<Sequence> listSequences = new ArrayList<>(sequences.length);
		Collections.addAll(listSequences, sequences);

		Piece piece = new Piece("Super Mario Theme", listSequences, 100, 1500);

		return piece;
	}

}
